package com.tsfyun.common.base.config;

import com.alibaba.fastjson.JSON;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.http.server.ServletServerHttpRequest;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

import java.util.Objects;

/**
 * controller响应增强处理
 */
@ControllerAdvice
public class ControllerResponseBodyAdvice implements ResponseBodyAdvice {

    @Override
    public boolean supports(MethodParameter returnType, Class converterType) {
        return true;
    }

    @Override
    public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, Class selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
        //增加空判断，把响应信息放到request对象中
        if(Objects.nonNull(body)) {
            String bodyStr = JSON.toJSONString(body);
            if (request instanceof ServletServerHttpRequest) {
                ((ServletServerHttpRequest) request).getServletRequest().setAttribute("body", bodyStr);
            }
        }
        return body;
    }
}